package br.ufrj.neg.artigo.servlet;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.velocity.Template;
import org.apache.velocity.context.Context;
import org.apache.velocity.tools.view.VelocityViewServlet;

import br.ufrj.neg.artigo.bean.ArtigoBean;
import br.ufrj.neg.artigo.model.ArtigoModel;
import br.ufrj.neg.bean.Idioma;
import br.ufrj.neg.constants.General;
import br.ufrj.neg.servlet.PageContext;

public class ListarArtigoParteExterna extends VelocityViewServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
			Idioma idioma = (Idioma) request.getAttribute("idioma");
		
			ArtigoModel aM = new ArtigoModel();
			
			ArrayList<ArtigoBean> artigos = new ArrayList<ArtigoBean>();
			artigos = aM.getArtigosAtivos(new ArtigoBean(idioma));
			
			Context context = createContext(request, response);
			fillContext(context, request);
			
			context.put("pageContext",new PageContext(request));
			context.put("artigos",artigos);
			
			Template template = getTemplate("templates/externo/artigos/listaArtigoExterno.vm");
			try {
				mergeTemplate(template, context, response);
			} catch (IOException e) {
				e.printStackTrace();
			}
			
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
		try {
			HttpSession session = request.getSession(false);
			
			Idioma idioma = (Idioma) request.getAttribute("idioma");
			
			String idArtigoDownload = request.getParameter("idArtigoDownload");
			ArtigoModel aM = new ArtigoModel();
			
			ArtigoBean aB = new ArtigoBean(idioma);
			aB.setId( Integer.parseInt(idArtigoDownload) );
			aB = aM.getArtigo(aB);

			//response.setContentType("application/pdf");
			
			
			response.setContentType("application/pdf");
			response.setHeader("Content-Disposition","attachment; filename="+ aB.getNome() + ".pdf");
						

			ServletOutputStream outputStream = response.getOutputStream();
			response.setContentLength(aB.getArtigoAsByte().length);
			outputStream.write(aB.getArtigoAsByte());
			outputStream.flush();
			outputStream.close();
			
			response.sendRedirect("/eneg/br/artigo.listar.externa");

		} catch (Exception e) {
			System.out.println(e);
			request.getRequestDispatcher(General.TELA_ERRO_500).forward(request,	response);
		}
	}
}
		
